import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, In, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateIssuesDto, UpdateIssuesDto, QueryIssuesDto } from './dto/issues.dto';
import { IssuesEntity } from './entities/issues.entity';
import { isEmpty } from 'src/common/utils';

@Injectable()
export class IssuesService {
  constructor(
    @InjectRepository(IssuesEntity)
    private readonly issuesEntityRep: Repository<IssuesEntity>,
  ) {}

  async create(createIssuesDto: CreateIssuesDto) {
    const res = await this.issuesEntityRep.save(createIssuesDto);
    return ResultData.ok(res);
  }

  async findAll(query: QueryIssuesDto) {
    const entity = this.issuesEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.id)) {
      entity.andWhere('entity.id = :id', { id: query.id });
    }
    if (!isEmpty(query.question)) {
      entity.andWhere('entity.question = :question', { question: query.question });
    }
    if (!isEmpty(query.hint)) {
      entity.andWhere('entity.hint = :hint', { hint: query.hint });
    }
    if (!isEmpty(query.delFlag)) {
      entity.andWhere('entity.delFlag = :delFlag', { delFlag: query.delFlag });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.createTime[0], end: query.createTime[1] });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', { start: query.updateTime[0], end: query.updateTime[1] });
    }
    entity.select(['entity.id', 'entity.question', 'entity.hint']);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  private lastReturnedIdsMap: Map<number, number[]> = new Map();

  async randList(userId: number) {
    const entity = this.issuesEntityRep.createQueryBuilder('entity');
    const whereConditions = { delFlag: '0' };
    entity.where(whereConditions);

    // 获取该用户上次返回的 ID 列表
    const lastReturnedIds = this.lastReturnedIdsMap.get(userId) || [];
    if (lastReturnedIds.length > 0) {
      entity.andWhere('entity.id NOT IN (:...ids)', { ids: lastReturnedIds });
    }

    entity.select(['entity.id', 'entity.question', 'entity.hint']);
    entity.orderBy('RAND()').limit(6);

    const list = await entity.getMany();

    // 更新该用户最后返回的 ID 列表
    this.lastReturnedIdsMap.set(
      userId,
      list.map((item) => item.id),
    );

    return ResultData.ok({
      list,
      total: list.length,
    });
  }

  async findOne(id: number) {
    const res = await this.issuesEntityRep.findOne({
      where: {
        delFlag: '0',
        id: id,
      },
    });
    return ResultData.ok(res);
  }

  async update(updateIssuesDto: UpdateIssuesDto) {
    const res = await this.issuesEntityRep.update({ id: updateIssuesDto.id }, updateIssuesDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async remove(ids: number[]) {
    const res = await this.issuesEntityRep.update(
      { id: In(ids) },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }
}
